package com.pospi.util;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.dao.GoodsDao;
import com.pospi.dto.GiveBeen;
import com.pospi.dto.GoodsDto;
import com.pospi.dto.ProGoodsBeen;
import com.pospi.dto.Promotionbeen;
import com.pospi.dto.ReduceProBeen;
import com.pospi.dto.SingleProBeen;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.login.Constant;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class PromotionUtil {
    private GoodsDao goodsDao;

    public PromotionUtil(Context context) {
        down(context);
        goodsDao = new GoodsDao(context);
    }

    private List<Promotionbeen> promotionbeens = new ArrayList<>();
    private List<ReduceProBeen> reduceProBeens = new ArrayList<>();
    private List<ProGoodsBeen> proGoodsBeens = new ArrayList<>();
    private List<GiveBeen> giveBeens = new ArrayList<>();
    private List<SingleProBeen> singleProBeens = new ArrayList<>();


    private List<Promotionbeen> pros = new ArrayList<>();


    //获取有效时间段促销
    public void getUsePro() {
        for (Promotionbeen pro : pros) {
            if (checktime(pro.getStarttime(), pro.getEndtime()) &&
                    checkDetailTime(pro.getStime(), pro.getEtime()) &&
                    checkWeek(getWeekOfDate(), pro)&&pro.getCustomerlimit().equals("0")) {
                promotionbeens.add(pro);
            }
        }
    }

    public void getUsePro(String vipid) {
        for (Promotionbeen pro : pros) {
            if (checktime(pro.getStarttime(), pro.getEndtime()) &&
                    checkDetailTime(pro.getStime(), pro.getEtime()) &&
                    checkWeek(getWeekOfDate(), pro)&&pro.getCustomerlimit().equals(vipid)) {
                promotionbeens.add(pro);
            }
        }
    }


    //单品促销价
    public void checkSinglePro(GoodsDto dto) {
        for (SingleProBeen proBeen : singleProBeens) {
            if (dto.getSid().equals(proBeen.getGoodsid())) {
                for (Promotionbeen promotionbeen : promotionbeens) {
                    if (proBeen.getMid().equals(promotionbeen.getId())) {
                        if (promotionbeen.getPtype().equals("4")) {//单品促销
                            dto.setProType(Constant.PRO_SINGLE_REDUCE);
                            dto.setProPrice(Double.parseDouble(proBeen.getPoplsj()));

                            if (proBeen.getSingnum().equals("0")) {
                                dto.setSingnum(9999);//优惠数量限制
                            } else {
                                dto.setSingnum(Integer.parseInt(proBeen.getSingnum()));//优惠数量限制
                            }
                            dto.setMuchnum(Integer.parseInt(proBeen.getMuchnum()));
                            if (dto.getNum() <= dto.getMuchnum()) {
                                dto.setCxzk(0);
                            } else {
                                dto.setCxzk(DoubleSave.doubleSaveTwo(dto.getPrice() * dto.getNum() - dto.getNum() * dto.getProPrice()));
                            }

                        } else if (promotionbeen.getPtype().equals("5")) {//单品折扣
                            dto.setProType(Constant.PRO_SINGLE_DISCOUNT);
                            dto.setProDiscout(Double.parseDouble(proBeen.getPoplsj()) / 100);
                            dto.setCxzk(dto.getPrice() * (1 - dto.getProDiscout()));
                        } else if (promotionbeen.getPtype().equals("6")) {//第n件促销
                            dto.setProType(Constant.PRO_N_REDUCE);
                            dto.setProPrice(Double.parseDouble(proBeen.getPoplsj()));
                            dto.setMuchnum(Integer.parseInt(proBeen.getMuchnum()));

                        }

                    }
                }

            }
        }

    }

    //买指定单个商品赠送指定商品
    public List<GoodsDto> checkGivePro(GoodsDto dto) {
        List<GoodsDto> list = new ArrayList<>();

        ok:
        for (ProGoodsBeen been : proGoodsBeens) {
            if (dto.getSid().equals(been.getLeftproid()) && been.getLeftlogic().equals("2")) {
                for (Promotionbeen promotionbeen : promotionbeens) {
                    if (been.getRuleid().equals(promotionbeen.getId())) {//找到对应规则
                        if (promotionbeen.getPtype().equals("3")) { //买赠,开始找赠品
                            for (ProGoodsBeen been1 : proGoodsBeens) {
                                if (been.getRuleid().equals(been1.getRuleid()) && been1.getLeftlogic().equals("0")) {//找到赠品
                                    GoodsDto goodsDto = goodsDao.selectGoodsbyId(been1.getRightproid());
                                    if (goodsDto != null) {
                                        goodsDto.setProType(Constant.PRO_ZP);
                                        goodsDto.setNum(Double.parseDouble(been1.getRightnum()));
                                        goodsDto.setPrice(0);
                                        goodsDto.setOldPrice(0);
                                        goodsDto.setLogic(been1.getRightlogic());
                                        list.add(goodsDto);
                                    }
                                }
                            }
                            //z赠品全部找完
                            break ok;

                        }
                    }
                }
            }
        }
        return list;
    }


    //买指定范围商品赠送指定商品
    public List<GoodsDto> check(List<GoodsDto> dtos) {//a,d
        List<GoodsDto> list = new ArrayList<>();
        ok:
        for (Promotionbeen promotionbeen : promotionbeens) {
            if (promotionbeen.getPtype().equals("3")) {//买A+b赠


                List<ProGoodsBeen> leftBeens = new ArrayList<>();//获取组合商品a ,b
                List<ProGoodsBeen> rightBeens = new ArrayList<>();//获取组合赠品c,d
                for (ProGoodsBeen been : proGoodsBeens) {
                    if (been.getRuleid().equals(promotionbeen.getId()) && been.getLeftlogic().equals("1")) {
                        leftBeens.add(been);
                    }
                    if (been.getRuleid().equals(promotionbeen.getId()) && been.getLeftlogic().equals("0")) {
                        rightBeens.add(been);
                    }
                }
                int i = 0;
                for (ProGoodsBeen been : leftBeens) {
                    for (GoodsDto dto : dtos) {
                        if (been.getLeftproid().equals(dto.getSid())) {
                            i++;
                        }
                    }
                }
                if (i == leftBeens.size()&&leftBeens.size()!=0) {//匹配到所有商品
                    for (ProGoodsBeen been : rightBeens) {
                        GoodsDto goodsDto = goodsDao.selectGoodsbyId(been.getRightproid());
                        if (goodsDto != null) {
                            goodsDto.setProType(Constant.PRO_ZP);
                            goodsDto.setNum(Double.parseDouble(been.getRightnum()));
                            goodsDto.setPrice(0);
                            goodsDto.setOldPrice(0);
                            goodsDto.setLogic(been.getRightlogic());
                            list.add(goodsDto);
                        }


                    }
                    break ok;
                }


            }
        }
        return list;

    }

    //优惠整单金额或折扣
    public String checkbill(double ys) {
        String discount = "0";
        for (ReduceProBeen proBeen : reduceProBeens) {
            for (Promotionbeen promotionbeen : promotionbeens) {
                if (proBeen.getMid().equals(promotionbeen.getId()) && proBeen.getProlimit().equals("1")) {
                    if (promotionbeen.getPtype().equals("1")) {//优惠
                        if (Double.parseDouble(proBeen.getStartamount()) <= ys) {
                            discount = proBeen.getDiscountamount();
                        }

                    } else if (promotionbeen.getPtype().equals("2") && proBeen.getProlimit().equals("1")) {//折扣
                        if (Double.parseDouble(proBeen.getStartamount()) <= ys) {
                            discount = proBeen.getDiscountamount() + "%";
                        }

                    }
                }
            }
        }
        return discount;
    }

    //优惠指定多个商品的总优惠
    public String chekDetail(List<GoodsDto> dtos) {
        String yh = "0";
        ok:
        for (Promotionbeen promotionbeen : promotionbeens) {
            if (promotionbeen.getPtype().equals("1")) {//买A+b减
                for (ReduceProBeen proBeen : reduceProBeens) {
                    if (promotionbeen.getId().equals(proBeen.getMid()) && proBeen.getProlimit().equals("2")) {//找到整单优惠表


                        List<ProGoodsBeen> leftBeens = new ArrayList<>();//获取组合商品a ,b
                        for (ProGoodsBeen been : proGoodsBeens) {
                            if (been.getRuleid().equals(proBeen.getMid())) {
                                leftBeens.add(been);
                            }

                        }

                        int i = 0;
                        double ys = 0;
                        for (ProGoodsBeen been : leftBeens) {
                            for (GoodsDto dto : dtos) {
                                if (been.getLeftproid().equals(dto.getSid())) {
                                    ys += dto.getPrice() * dto.getNum();
                                    i++;
                                }
                            }
                        }
                        if (i == leftBeens.size() && Double.parseDouble(proBeen.getStartamount()) <= ys) {//匹配到所有商品且金额大于指定金额
                            yh = proBeen.getDiscountamount();

                            break ok;
                        }


                    }
                }
            } else if (promotionbeen.getPtype().equals("2")) {//买A+b折
                for (ReduceProBeen proBeen : reduceProBeens) {
                    if (promotionbeen.getId().equals(proBeen.getMid()) && proBeen.getProlimit().equals("2")) {//找到整单优惠表


                        List<ProGoodsBeen> leftBeens = new ArrayList<>();//获取组合商品a ,b
                        for (ProGoodsBeen been : proGoodsBeens) {
                            if (been.getRuleid().equals(proBeen.getMid())) {
                                leftBeens.add(been);
                            }

                        }

                        int i = 0;
                        double ys = 0;
                        for (ProGoodsBeen been : leftBeens) {
                            for (GoodsDto dto : dtos) {
                                if (been.getLeftproid().equals(dto.getSid())) {
                                    ys += dto.getPrice() * dto.getNum();
                                    i++;
                                }
                            }
                        }
                        if (i == leftBeens.size() && Double.parseDouble(proBeen.getStartamount()) <= ys) {//匹配到所有商品且金额大于指定金额
                            yh = String.valueOf((1 - (Double.parseDouble(proBeen.getDiscountamount())/100)) * ys);
                        }

                    }
                }
            }


        }

        return yh;
    }


    //判断日期是否符合
    public static boolean checktime(String sTime, String eTime) {
        Date nowDate = new Date();
        Date sDate = null;
        Date eDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        try {
            sDate = sdf.parse(sTime);
            eDate = sdf.parse(eTime);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(eDate);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            eDate = calendar.getTime();
            if ((nowDate.before(eDate)) && (nowDate.after(sDate))) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return false;
    }

    //判断时间是否符合
    public static boolean checkDetailTime(String sTime, String eTime) {
        String curTime = GetData.getHHmmssTimet();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            long ntime = sdf.parse(curTime).getTime();
            long stime = sdf.parse(sTime).getTime();
            long etime = sdf.parse(eTime).getTime();
            if (ntime >= stime && ntime <= etime) {
                return true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return false;

    }

    //盘段星期是否符合
    public static boolean checkWeek(String week, Promotionbeen been) {
        switch (week) {
            case "星期日":
                if (been.getWeek7().equals("1")) {
                    return true;
                }
                break;
            case "星期一":
                if (been.getWeek1().equals("1")) {
                    return true;
                }
                break;
            case "星期二":
                if (been.getWeek2().equals("1")) {
                    return true;
                }
                break;
            case "星期三":
                if (been.getWeek3().equals("1")) {
                    return true;
                }
                break;
            case "星期四":
                if (been.getWeek4().equals("1")) {
                    return true;
                }
                break;
            case "星期五":
                if (been.getWeek5().equals("1")) {
                    return true;
                }
                break;
            case "星期六":
                if (been.getWeek6().equals("1")) {
                    return true;
                }
                break;
        }

        return false;
    }

    public static String getWeekOfDate() {
        Date dt = new Date();
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    //下载促销
    private void down(Context context) {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "activity.api");
        params.put("fun", "getactivity");
        params.put("storeid", SPHelper.getInstance().getString(Constant.STORE_ID));
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                savePro(Response);
            }
        });

    }


    //存储活动
    private void savePro(String s) {

        try {
            JSONObject object = new JSONObject(s);
            JSONObject result = object.getJSONObject("result");
            pros = new Gson().fromJson(result.getJSONArray("head").toString(), new TypeToken<List<Promotionbeen>>() {
            }.getType());
            Log.i("data", result.getJSONArray("head").toString());
            reduceProBeens = new Gson().fromJson(result.getJSONArray("discou").toString(), new TypeToken<List<ReduceProBeen>>() {
            }.getType());
            Log.i("data", result.getJSONArray("discou").toString());
            proGoodsBeens = new Gson().fromJson(result.getJSONArray("goods").toString(), new TypeToken<List<ProGoodsBeen>>() {
            }.getType());
            Log.i("data", result.getJSONArray("goods").toString());
            giveBeens = new Gson().fromJson(result.getJSONArray("nplusn").toString(), new TypeToken<List<GiveBeen>>() {
            }.getType());
            Log.i("data", result.getJSONArray("nplusn").toString());
            singleProBeens = new Gson().fromJson(result.getJSONArray("mgooddiscou").toString(), new TypeToken<List<SingleProBeen>>() {
            }.getType());

            Log.i("data", "活动存储完成" + pros.size() + "-----" + reduceProBeens.size() + "-----" + proGoodsBeens.size() + "-----" + giveBeens.size() + "-----" + singleProBeens.size());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
